package jmercury;

import dblib.DB;
import dblib.NewConnectDialog;
import dblib.PDM;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;

public class main {

    public static void main(String[] args) {
        // Logger
        try {
            Logger.getLogger("").addHandler(new FileHandler("errorlog.xml"));
        } catch (IOException | SecurityException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Look and feel
        try {
            UIManager.setLookAndFeel(new NimbusLookAndFeel());
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Initialisation and Properties
        Vars.PropPath = System.getProperty("user.home") + "/.JMercury";
        Vars.PropFileName = Vars.PropPath + "/Options.xml";
        File dir = new File(Vars.PropPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            Vars.setHostID(java.net.InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

        Boolean NeedConnect = false;
        Vars.LoadProperties();

        if (!Vars.prop.containsKey("Username")) {
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("Userpass")) {
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("DB_URL")) {
            NeedConnect = true;
        }
        if (!Vars.prop.containsKey("LogW1")) {
            Vars.prop.setProperty("LogW1", "130");
        }
        if (!Vars.prop.containsKey("LogW2")) {
            Vars.prop.setProperty("LogW2", "120");
        }
        if (!Vars.prop.containsKey("LogW3")) {
            Vars.prop.setProperty("LogW3", "180");
        }
        if (!Vars.prop.containsKey("LogW4")) {
            Vars.prop.setProperty("LogW4", "570");
        }
        if (!NeedConnect) {
            DB.init(Vars.prop.getProperty("Username"), Vars.prop.getProperty("Userpass"), Vars.prop.getProperty("DB_URL"));
            if (!new DB().checkConnection()) {
                NeedConnect = true;
            }
        }
        if (NeedConnect) {
            NewConnectDialog newConnDlg = new NewConnectDialog(null, true);

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `meters` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`name` VARCHAR(4096) NOT NULL, "
                    + "`group_id` INT NOT NULL, "
                    + "`serial` VARCHAR(45) NOT NULL, "
                    + "`port` VARCHAR(1024) NOT NULL, "
                    + "`address` INT NOT NULL, "
                    + "`ki` INT NOT NULL, "
                    + "`ku` INT NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`)) ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `metergroups` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`groupname` VARCHAR(4096) NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`)) ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `monthdata` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`meter_id` INT NOT NULL, "
                    + "`Aplus` DOUBLE NOT NULL, "
                    + "`Rplus` DOUBLE NOT NULL, "
                    + "`AplusOnBeg` DOUBLE NOT NULL, "
                    + "`RplusOnBeg` DOUBLE NOT NULL, "
                    + "`monthDT` DATETIME NOT NULL, "
                    + "`wet` TINYINT(1) NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`), "
                    + "INDEX `i_meter_id` (`meter_id` ASC)"
                    + ") ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `daydata` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`meter_id` INT NOT NULL, "
                    + "`Aplus` DOUBLE NOT NULL, "
                    + "`Rplus` DOUBLE NOT NULL, "
                    + "`dayDT` DATETIME NOT NULL, "
                    + "`wet` TINYINT(1) NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`), "
                    + "INDEX `i_meter_id` (`meter_id` ASC), "
                    + "INDEX `i_wet` (`wet`), "
                    + "INDEX `i_id_wet_hide` (`hide`,`wet`,`meter_id`)"
                    + ") ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `commands` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`meter_id` INT NOT NULL, "
                    + "`command` VARCHAR(45) NOT NULL, "
                    + "`status` VARCHAR(45) NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`), "
                    + "INDEX `i_meter_id` (`meter_id` ASC)"
                    + ") ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `avgars` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`meter_id` INT NOT NULL, "
                    + "`Aplus` DOUBLE NOT NULL, "
                    + "`Aminus` DOUBLE NOT NULL, "
                    + "`Rplus` DOUBLE NOT NULL, "
                    + "`Rminus` DOUBLE NOT NULL, "
                    + "`arPeriod` INT NOT NULL, "
                    + "`arDT` DATETIME NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`), "
                    + "INDEX `i_meter_id` (`meter_id`), "
                    + "INDEX `i_arDT` (`arDT`)"
                    + ") ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `metervals` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`meter_id` INT NOT NULL, "
                    + "`U1` DOUBLE NOT NULL, "
                    + "`U2` DOUBLE NOT NULL, "
                    + "`U3` DOUBLE NOT NULL, "
                    + "`I1` DOUBLE NOT NULL, "
                    + "`I2` DOUBLE NOT NULL, "
                    + "`I3` DOUBLE NOT NULL, "
                    + "`P1` DOUBLE NOT NULL, "
                    + "`P2` DOUBLE NOT NULL, "
                    + "`P3` DOUBLE NOT NULL, "
                    + "`Q1` DOUBLE NOT NULL, "
                    + "`Q2` DOUBLE NOT NULL, "
                    + "`Q3` DOUBLE NOT NULL, "
                    + "`S1` DOUBLE NOT NULL, "
                    + "`S2` DOUBLE NOT NULL, "
                    + "`S3` DOUBLE NOT NULL, "
                    + "`F` DOUBLE NOT NULL, "
                    + "`valDT` DATETIME NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`), "
                    + "INDEX `i_meter_id` (`meter_id` ASC)"
                    + ") ENGINE = InnoDB");

            newConnDlg.AddSQL("CREATE TABLE IF NOT EXISTS `logs` ("
                    + "`k` INT NOT NULL AUTO_INCREMENT, "
                    + "`hostid` VARCHAR(512) NOT NULL, "
                    + "`logtype` INT NOT NULL, "
                    + "`class` VARCHAR(4096) NOT NULL, "
                    + "`logtext` VARCHAR(4096) NOT NULL, "
                    + "`dt` DATETIME NOT NULL, "
                    + "`hide` TINYINT(1) NOT NULL, "
                    + "PRIMARY KEY (`k`)) ENGINE = InnoDB");

            newConnDlg.SetStrings(
                    "Для работы программы необходимо подключиться к серверу баз даных.",
                    "Все таблицы и настройки успешно созданы.");

            newConnDlg.setLocationRelativeTo(null);
            newConnDlg.setVisible(true);
            if (newConnDlg.getResult().equals("False")) {
                Runtime.getRuntime().exit(1);
            }
            Vars.prop.setProperty("Username", newConnDlg.getUsername());
            Vars.prop.setProperty("Userpass", newConnDlg.getPassword());
            Vars.prop.setProperty("DB_URL", newConnDlg.getURL());
            Vars.SaveProperties();
        } else {
            DB.init(Vars.prop.getProperty("Username"),
                    Vars.prop.getProperty("Userpass"),
                    Vars.prop.getProperty("DB_URL"));
        }
        PDM pdm = new PDM("em",
                Vars.prop.getProperty("Username"),
                Vars.prop.getProperty("Userpass"),
                Vars.prop.getProperty("DB_URL"));
        pdm.addConnInstance("log",
                Vars.prop.getProperty("Username"),
                Vars.prop.getProperty("Userpass"),
                Vars.prop.getProperty("DB_URL"));
        long metergroupscount = (long) pdm.getScalar("em", "SELECT COUNT(*) FROM metergroups WHERE hide = 0");
        if (metergroupscount == 0) {
            pdm.executeNonQuery("em", "INSERT INTO metergroups (groupname, hide) VALUES ('" + DB.getHexString("Все") + "', false)");
        }
        // End of Initialisation and Properties

        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                MainFrame frm = new MainFrame();
                Logs.log(3, getClass().toString(), "Запуск программы");
                frm.setLocationRelativeTo(null);
                frm.setVisible(true);
            }
        });
    }
}
